package com.thf.message;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Properties;

public class SendToEmail {

    public static String sendMessage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 收件人的电子邮件 ID
        String to = req.getParameter("email");

        //回复邮件内容
        String content = req.getParameter("describe");

        // 发件人的电子邮件 ID
        String from = "frpeizhiwei@163.com";

        // 发件人使用发邮件的电子信箱服务器
        String host = "smtp.163.com";

        // 获取系统的属性
        Properties properties = System.getProperties();

        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);

        // 获取默认的 Session 对象
        properties.setProperty("mail.smtp.auth", "true");// 指定验证为true是否需要身份验证
        MyAuthenticator myauth = new MyAuthenticator("frpeizhiwei@163.com", "PDOSBCKGUHGHEHYY");
        Session session = Session.getDefaultInstance(properties, myauth);
//        Session session = Session.getDefaultInstance(properties);

        // 设置响应内容类型
        resp.setContentType("text/html");

        try{
            // 创建一个默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);
            // 设置 From: header field of the header.
            message.setFrom(new InternetAddress(from));
            // 设置 To: header field of the header.
            message.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(to));
            // 设置 Subject: header field
            message.setSubject("来自后台的回复");
            // 现在设置实际消息
            message.setText(content);
            // 发送消息
            Transport.send(message);
        }catch (MessagingException mex) {
            mex.printStackTrace();
            return "error";
        }
        return "success";
    }
}
